package com.liujie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liujie.common.R;
import com.liujie.entity.User;
import com.liujie.service.UserService;
import com.liujie.utils.MailUtils;
import com.liujie.utils.SMSUtils;
import com.liujie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;//使用Redis缓存

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        log.info("---------发送手机验证码--------");
        String phone = user.getPhone();
        log.info("手机号："+phone);
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码："+code);
            //发送短信，阿里云测试一天只能发10条，一条5毛
            /*SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);*/
            //将生成的验证码保存到session中
            //session.setAttribute(phone,code);
            //将生成的验证码缓存到Redis中，并设置成三分钟
            redisTemplate.opsForValue().set(phone,code,3, TimeUnit.MINUTES);

            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    @PostMapping("/sendEmailMsg")
    public R<String> sendEmailMsg(@RequestBody User user, HttpSession session){
        String email = user.getEmail();
        log.info("邮箱："+email);
        if (StringUtils.isNotEmpty(email)){
            String code = ValidateCodeUtils.digitalVerificationVode();//六位数字验证码
            log.info("验证码："+code);
            //发送邮件，使用的QQ邮箱
            MailUtils.sendMail(email,code);
            //将生成的验证码保存到session中
            //session.setAttribute(email,code);
            //将生成的验证码缓存到Redis中，并设置成三分钟
            redisTemplate.opsForValue().set(email,code,3, TimeUnit.MINUTES);

            return R.success("验证码发送成功");
        }
        return R.error("验证码发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取验证码
        //Object codeInSession = session.getAttribute(phone);
        //从Redis中获取缓存验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        if (codeInSession!=null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //如果用户登录成功，删除Redis中缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("验证码错误");
    }

    @PostMapping("/loginEmail")
    public R<User> loginEmail(@RequestBody Map map, HttpSession session){
        String email = map.get("email").toString();
        String code = map.get("code").toString();
        //从session中获取验证码
        //Object codeInSession = session.getAttribute(email);
        //从Redis中获取缓存验证码
        Object codeInSession = redisTemplate.opsForValue().get(email);

        if (codeInSession!=null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
            lqw.eq(User::getEmail,email);
            User user = userService.getOne(lqw);
            if (user==null){
                user=new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //如果用户登录成功，删除Redis中缓存的验证码
            redisTemplate.delete(email);
            return R.success(user);
        }
        return R.error("验证码错误");
    }

    /**
     * 用户退出登录
     * @param request 移除登录时存储在session中的数据
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
